/* eslint-disable array-bracket-spacing */
/* eslint-disable no-dupe-class-members */
/* eslint-disable indent */
'use strict'

const Service = require('egg').Service
const dayjs = require('dayjs')
const { Op } = require('sequelize')

// 信息要返回的字段
const attributes = ['id', 'm_bid', 'pid', 'upmachine_time', 'computer_name', 'area_name']
const member_attributes = ['id', 'mid', 'openid', 'unionid', 'phone', 'nickname', 'avatar', 'sex', 'birthday', 'register_time', 'last_login_time', 'level_name', 'subscribe', 'subscribe_time', 'pid', 'card_id', 'balance', 'recharge_amount', 'consume_time', 'week_count', 'count', 'status']
const place_attributes = ['barname', 'barcode']

class UpmachineRecordService extends Service {

    // 查询所有列表
    async getUpmachineRecordList(params) {
        const { model, helper } = this.ctx
        const currentPage = params?.pageIndex ?? 1
        const pageSize = params?.pageSize ?? 50
        const where = {}
        if (params.pid) {
            where.pid = params.pid
        }
        if (params.start_time && params.end_time) {
            where.upmachine_time = {
                [Op.between]: [params.start_time, params.end_time]
            }
        }

        return await model.UpmachineRecord.findAndCountAll({
            where,
            offset: (currentPage - 1) * pageSize, // 计算分页偏移量
            limit: pageSize,
            attributes,
            include: [
                {
                    model: model.Place,
                    // as: 'place',
                    attributes: place_attributes
                },
                {
                    model: model.Member,
                    // as: 'member',
                    attributes: member_attributes
                }
            ],
            order: [
                ['computer_name', 'ASC'],
                ['upmachine_time', 'DESC']
            ]
        })
            .then(async result => {
                if (result) {
                    return {
                        list: result.rows,
                        total: result.count
                    }
                }
                helper.failed(1004, null, '查询上机记录失败')
                return false
            })
            .catch(async error => {
                if (error?.original?.sqlMessage) {
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors) {
                    helper.failed(1001, null, JSON.stringify(error.errors))
                } else {
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })
    }

    // 新增
    async createUpmachineRecord(params) {
        const { model, helper, logger } = this.ctx
        let flag = 0
        // 使用事务
        const t = await model.transaction()
        try {
            // 写入会员表
            const [member, isCreated] = await model.Member.findOrCreate({
                where: {
                    mid: params.mid,
                    pid: params.pid
                },
                defaults: {
                    ...params,
                    register_time: params.upmachine_time,
                    last_login_time: params.upmachine_time,
                    week_count: 1, // 本周消费次数
                    count: 1 // 总消费次数
                },
                transaction: t
            })
            if (!isCreated && member) {
                const weekStart = dayjs().day(1).startOf('day')
                const isCurrentWeek = dayjs(member.last_login_time).isAfter(weekStart) // 判断是否为本周上机
                await member.update({
                    ...params,
                    last_login_time: params.upmachine_time,
                    week_count: isCurrentWeek ? member.week_count + 1 : 1, // 本周消费次数
                    count: member.count + 1 // 总消费次数
                }, {
                    transaction: t
                })
            }
            flag = 1

            const result = await model.UpmachineRecord.findOne({
                where: {
                    pid: params.pid,
                    m_bid: member.id,
                    upmachine_time: params.upmachine_time
                },
                // include: [
                //     {
                //         model: model.Member,
                //         where: {
                //             mid: params.mid
                //         }
                //     }
                // ],
                transaction: t,
                attributes
            })
            if (result) {
                await t.commit()
                helper.failed(1003, null, '上机记录已存在')
                return false
            }
            flag = 2

            // 写入上机记录表
            const record = await model.UpmachineRecord.create({
                ...params,
                m_bid: member.id
            }, {
                include: [
                    {
                        model: model.Member,
                        attributes: ['mid', 'card_id', 'balance']
                    }
                ],
                transaction: t
            })
            flag = 3

            // 如果有僵尸在线会员，先删除在线会员表
            const records = await model.OnlineMember.findAll({
                where: {
                    pid: params.pid,
                    m_bid: member.id
                },
                transaction: t
            })
            for (const item of records) {
                await item.destroy({
                    transaction: t
                })
            }
            flag = 4

            // 写入在线会员表
            await model.OnlineMember.create({
                ...params,
                m_bid: member.id
            }, {
                transaction: t
            })
            flag = 5

            await t.commit()
            flag = 6

            const res = await member.toJSON()
            res.computer_name = params?.computer_name ? params.computer_name : ''
            res.area_name = params?.area_name ? params.area_name : ''
            res.upmachine_time = params?.upmachine_time ? params.upmachine_time : ''
            return res
        } catch (error) {
            await t.rollback() // 回滚

            if (error?.original?.sqlMessage) {
                logger.error(`上机操作失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${error?.original?.sqlMessage}`)
                helper.failed(1001, null, error?.original?.sqlMessage)
            } else if (error?.errors) {
                logger.error(`上机操作失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${JSON.stringify(error.errors)}`)
                helper.failed(1001, null, JSON.stringify(error.errors))
            } else {
                logger.error(`上机操作失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${JSON.stringify(error)}`)
                helper.failed(1001, null, JSON.stringify(error))
            }

            return false
        }
    }

}

module.exports = UpmachineRecordService
